/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bittorentlike;

import define.Define;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.*;
import java.awt.*;

/**
 *
 * @author Xuan Cau
 */
public class MainControl extends javax.swing.JFrame {

    /**
     * Creates new form MainControl
     */
    private int _num_file;
    private int _num_host;
    
    private byte[][] _all_chunk;
    
    private String _file_name;
    private String _host_name;
    public MainControl() {
        initComponents();
    }
    public void Init()
    {
       this.setTitle("Bittorent Like");
       Receive re = new Receive(this);
       re.start();
       timer time = new timer(this);
       time.start();
       
       _all_chunk = new byte[1024][];
    }
    public void NewChunk(byte[] data)
    {
        for(int i = 0;i<_all_chunk.length;i++)
        {
            if(_all_chunk[i] == null)
            {
                _all_chunk[i] = data;
                break;
            }
        }
    }
    public byte[] GetChunk(byte[] sha)
    {
        for(int i = 0;i<_all_chunk.length;i++)
        {
            if(java.util.Arrays.equals(sha,Util.Utils.SHA1(_all_chunk[i])))
            {
                byte[] temp = _all_chunk[i];
                _all_chunk[i] = null;
                return temp;
            }
        }
        return null;
    }
    public void BeginDownload(byte[][] torrent)
    {
        ThreadDowload download = new ThreadDowload(this,_file_name,_host_name);
        download.SetFile(torrent);
        download.start();
    }
    public void InitDownloadFile(String host_name,String file_name)
    {
        _file_name = file_name;
        _host_name = host_name;

        byte[] host = host_name.getBytes();
        byte[] name = file_name.getBytes();
        ByteBuffer buf = ByteBuffer.allocate(2 + host.length + 2 + name.length);
        
        buf.putShort((short)host.length);
        buf.put(host);
        
        buf.putShort((short)name.length);
        buf.put(name);
        
        byte[] data = buf.array();
        Send send = new Send();
        send.SendDownloadTorrent(data);
    }
    public void SearchAllFile()
    {
      /* DefaultTableModel tm = (DefaultTableModel) this.table_host_file.getModel();
       int num_row = tm.getRowCount();
       for(int i = 0;i<num_row;i++)
           tm.removeRow(i);
       Send send = new Send();
       send.SendSearch();*/
    }
    public void AddHostName(String host_name,String address)
    {
        ItemHost item_host = new ItemHost();
        //item_host.setVisible(true);
        item_host.SetHostName(host_name);
        item_host.setIP(address);
        this.list.add(item_host);
        item_host.setBounds(10,10 + _num_host*48,670, 45);
        _num_host += 1;
    }
    public void AddFile(String host_name,String file_name)
    {
        ItemFile item_file = new ItemFile(this);
        //item_file.setVisible(true);
        item_file.SetFileName(host_name,file_name);
        this.list.add(item_file);
        item_file.setBounds(10,10 + _num_file*48, 670, 45);
        _num_file += 1;
       
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPopupMenu1 = new javax.swing.JPopupMenu();
        jButton1 = new javax.swing.JButton();
        bt_search = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        bt_host = new javax.swing.JButton();
        bt_file = new javax.swing.JButton();
        bt_upload = new javax.swing.JButton();
        bt_upload1 = new javax.swing.JButton();
        list = new javax.swing.JPanel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        jPopupMenu1.setComponentPopupMenu(jPopupMenu1);
        jPopupMenu1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jPopupMenu1.setInvoker(this);
        jPopupMenu1.setLabel("");
        jPopupMenu1.setPreferredSize(new java.awt.Dimension(100, 200));

        jButton1.setText("jButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(102, 102, 102));
        setForeground(new java.awt.Color(153, 153, 153));

        bt_search.setText("Tìm kiếm");

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));

        jPanel4.setBackground(new java.awt.Color(204, 204, 204));

        jLabel2.setText("Menu");

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        bt_host.setBackground(new java.awt.Color(204, 255, 0));
        bt_host.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bt_host.setForeground(new java.awt.Color(0, 51, 204));
        bt_host.setText("Host");
        bt_host.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_hostActionPerformed(evt);
            }
        });

        bt_file.setBackground(new java.awt.Color(255, 255, 153));
        bt_file.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bt_file.setForeground(new java.awt.Color(0, 51, 204));
        bt_file.setText("File");
        bt_file.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_fileActionPerformed(evt);
            }
        });

        bt_upload.setBackground(new java.awt.Color(255, 255, 153));
        bt_upload.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bt_upload.setForeground(new java.awt.Color(0, 51, 204));
        bt_upload.setText("Upload");
        bt_upload.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_uploadActionPerformed(evt);
            }
        });

        bt_upload1.setBackground(new java.awt.Color(255, 255, 153));
        bt_upload1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        bt_upload1.setForeground(new java.awt.Color(0, 51, 204));
        bt_upload1.setText("Torrent");
        bt_upload1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_upload1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(bt_host, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(bt_file, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bt_upload, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bt_upload1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bt_host, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(bt_file, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(bt_upload, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(bt_upload1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(30, Short.MAX_VALUE))
        );

        list.setBackground(new java.awt.Color(255, 255, 255));
        list.setAutoscrolls(true);

        javax.swing.GroupLayout listLayout = new javax.swing.GroupLayout(list);
        list.setLayout(listLayout);
        listLayout.setHorizontalGroup(
            listLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 680, Short.MAX_VALUE)
        );
        listLayout.setVerticalGroup(
            listLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        jMenuBar1.setBackground(new java.awt.Color(102, 102, 102));

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("About");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(0, 603, Short.MAX_VALUE)
                        .addComponent(bt_search))
                    .addComponent(list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(list, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(bt_search, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_hostActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_hostActionPerformed
        // TODO add your handling code here:
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        this.list.removeAll();
        _num_host = 0;
        Send send = new Send();
        send.SendHello();
    }//GEN-LAST:event_bt_hostActionPerformed

    private void bt_fileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_fileActionPerformed
        // TODO add your handling code here:
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
       _num_file = 0;
       this.list.removeAll();
       Send send = new Send();
       send.SendSearch();
    }//GEN-LAST:event_bt_fileActionPerformed

    private void bt_uploadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_uploadActionPerformed
        // TODO add your handling code here:
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        this.list.removeAll();
        Upload upload = new Upload();
        upload.setVisible(true);
        this.list.add(upload);
        upload.setBounds(40, 70, 400, 189);
    }//GEN-LAST:event_bt_uploadActionPerformed

    private void bt_upload1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_upload1ActionPerformed
        // TODO add your handling code here:
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        this.list.removeAll();
        chunk ck = new chunk();
        //ck.setVisible(true);
        this.list.add(ck);
        ck.setBounds(40, 70, 400, 189);
    }//GEN-LAST:event_bt_upload1ActionPerformed
     
    private void chooserAction(java.awt.event.ActionEvent evt) 
    {
       /* JFileChooser theFileChooser = (JFileChooser) evt.getSource();
        String command = evt.getActionCommand();
        if (command.equals(JFileChooser.APPROVE_SELECTION)) {
            File selectedFile = theFileChooser.getSelectedFile();
            String filename = selectedFile.getParent() + "\\" + selectedFile.getName();
            this.txt_path_file.setText(filename);
        }*/
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainControl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainControl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainControl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainControl.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainControl().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_file;
    private javax.swing.JButton bt_host;
    private javax.swing.JButton bt_search;
    private javax.swing.JButton bt_upload;
    private javax.swing.JButton bt_upload1;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JPanel list;
    // End of variables declaration//GEN-END:variables
}
